package com.demo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问，功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/index").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限默认会到登录页面
        http.formLogin();
        //防止网站工具: grt post
        http.csrf().disable();
        //开启了注销功能  跳到首页
        http.logout().logoutUrl("/");
        //定制记住我的参数！
        http.rememberMe().rememberMeParameter("remember");
        //定制登录页
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password");
    }

    //认证 spring boot 2.1.x 可以直接使用
    //密码编码:PasswordEncoder
    //在Spring secutiry 5.0+新增了很多加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //没有数据库 ，只有在这弄
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("m").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3").and()
                .withUser("r").password(new BCryptPasswordEncoder().encode("456")).roles("vip1","vip2").and()
                .withUser("c").password(new BCryptPasswordEncoder().encode("789")).roles("vip1");

    }
}
